package com.jl15988.chainlog.callback;

import com.jl15988.chainlog.model.ChainApiLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 默认接口监控回调实现
 */
public class DefaultChainApiCallback implements ChainApiCallback {

    private static final Logger logger = LoggerFactory.getLogger(DefaultChainApiCallback.class);

    @Override
    public void onChainComplete(ChainApiLog chainApiLog, HttpServletRequest request, HttpServletResponse response) {
        logger.info("API Monitor Complete: {}", formatMonitorInfo(chainApiLog));
    }

    @Override
    public void onChainException(ChainApiLog chainApiLog, HttpServletRequest request,
                                 HttpServletResponse response, Throwable exception) {
        logger.error("API Monitor Exception: {}", formatMonitorInfo(chainApiLog), exception);
    }

    private String formatMonitorInfo(ChainApiLog chainApiLog) {
        StringBuilder sb = new StringBuilder();
        sb.append("ID=").append(chainApiLog.getId())
                .append(", Method=").append(chainApiLog.getMethod())
                .append(", URL=").append(chainApiLog.getUrl())
                .append(", HttpMethod=").append(chainApiLog.getHttpMethod())
                .append(", ClientIP=").append(chainApiLog.getClientIp())
                .append(", Duration=").append(chainApiLog.getDuration()).append("ms")
                .append(", Success=").append(chainApiLog.isSuccess());

        if (chainApiLog.getModule() != null && !chainApiLog.getModule().isEmpty()) {
            sb.append(", Module=").append(chainApiLog.getModule());
        }

        if (chainApiLog.getOperationName() != null && !chainApiLog.getOperationName().isEmpty()) {
            sb.append(", Operation=").append(chainApiLog.getOperationName());
        }

        return sb.toString();
    }
}